//
//  LogInViewController.m
//  PCSchool
//
//  Created by Jayanta on 07/07/13.
//  Copyright (c) 2013 Jayanta. All rights reserved.
//

#import "LogInViewController.h"
#import "ASIHTTPRequest.h"

#define kNumberOfRowsInSection1 1

enum {
    kRowDropDownSelection = 0,
    kRowDropDownDisclosure,
    kRow1
};
#define kNumberOfSections 2

enum {
    kSection1 = 0,
    kSection2
};

/* set to 2 if you want to see how it behaves
 when having more cells in the same section
 */

#define kNumberOfRowsInSection2 1
enum {
    kRowDropDownCustom = 0,
    kS2Row1
};

@interface LogInViewController ()

@end

@implementation LogInViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}

- (void)viewDidLoad
{
   
    [super viewDidLoad];
    
    self.array4SchoolName = [NSMutableArray array];
    self.array4SchoolURL = [NSMutableArray array];
    
       
    [self createLoadingView];
    
    [self.appDelegate.dataModel sendRequestFor:SCHOOL_LIST from:self];
    
    
    // Do any additional setup after loading the view from its nib.
}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=YES;
    [super viewWillAppear:animated];
    
    NSLog(@"%@",NSStringFromClass(self.class));

}


-(void) viewDidAppear:(BOOL)animated
{
    //self.userNameTextField.text = @"ahernz14";
    //self.passwordTextField.text = @"password";
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark postData
-(id)postData
{
	NSMutableDictionary *aDict=[NSMutableDictionary dictionary];
	//NSString *str=[NSString stringWithFormat:@"%d",[anAgenda.entityId intValue]];
	[aDict setValue:self.userNameTextField.text forKey:USERID];
	[aDict setValue:self.passwordTextField.text forKey:PASSWORD];
    [aDict setValue:@"Padua" forKey:HOST_ADDRESS];
    
    @try {
        NSLog(@"ARA  %@",[self.appDelegate.arrayForStudentDetails valueForKey:@"MemberId"]);
        [aDict setValue:[self.appDelegate.arrayForStudentDetails valueForKey:@"MemberId"] forKey:UPDATED_USERID];
    }
    @catch (NSException *exception) {
        NSLog(@"EXC %@",exception);
    }
    @finally {
        [aDict setValue:[self.appDelegate.arrayForStudentDetails valueForKey:@"MemberId"] forKey:UPDATED_USERID];

    }

	return aDict;
	
}

-(void) notifyRequesterWithData:(id)aManager
{
    [self removeLoadingView];
    
    ConnectionManager* aCon = aManager;
    NSLog(@"RESPONSE DATA  %@",aCon.responseString);
    
    if ([aCon.aRequest error])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[[aCon.aRequest error] localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    
    else
    {
        if ([aCon.requestName isEqualToString:SCHOOL_LIST])
        {
            
            self.arrayForJsonData = [aCon.responseString objectFromJSONString];
            
            
            for (NSDictionary *dict in self.arrayForJsonData) {
                
                [self.array4SchoolName addObject:[dict valueForKey:@"Name"]];
                [self.array4SchoolURL addObject:[dict valueForKey:@"WebServiceURL"]];
                
            }
            
            
            NSLog(@"ARRAY %@ %@ %@",self.arrayForJsonData,self.array4SchoolName,self.array4SchoolURL);
            
            _dropDownSelection = [[VPPDropDown alloc] initSelectionWithTitle:@"Select School"
                                                                   tableView:self.schholSelectionTable
                                                                   indexPath:[NSIndexPath indexPathForRow:kRowDropDownSelection inSection:kSection1]
                                                                    delegate:self
                                                               selectedIndex:1
                                                               elementArrayTitles:self.array4SchoolName];
            
            [self.schholSelectionTable reloadData];
            
            _dropDownSelection.selectedIndex = 2;
            
            [self.appDelegate.userDefault setValue:[[self.arrayForJsonData objectAtIndex:_dropDownSelection.selectedIndex] valueForKey:@"WebServiceURL"] forKey:SELECTED_SCHOOL_URL];
            [self.appDelegate.userDefault synchronize];
            
            NSLog(@"BASEURL  %@",SUB_BASE_URL);

        }
        
        else if ([aCon.requestName isEqualToString:LOGIN])
        {
            self.appDelegate.arrayForStudentDetails = [aCon.responseString objectFromJSONString];
            NSLog(@"%@",self.appDelegate.arrayForStudentDetails);
            [self.appDelegate.userDefault setBool:YES forKey:LOGIN_SUCCESS];
            [self.appDelegate.userDefault setObject:self.appDelegate.arrayForStudentDetails forKey:LOGIN_USER_DETAILS];
            [self.appDelegate.userDefault synchronize];
            [self createLoadingView];
            [self.appDelegate.dataModel sendRequestFor:STUDENT_UDID_UPDATE from:self];
        }
        else if ([aCon.requestName isEqualToString:STUDENT_UDID_UPDATE])
        {
            NSLog(@"%@",aCon.responseString);
            [self.appDelegate addTabBarController];
        }
    }
    
    
}


#pragma mark - Button Action

- (IBAction)loginButtonAction:(id)sender
{
    if ([self.userNameTextField.text length] == 0 || [self.passwordTextField.text length] == 0) {
        
        [self showAlertMessage:@"UserName or Password cannot be empty"];
    }
    else{
        [self createLoadingView];
        [self.appDelegate.dataModel sendRequestFor:LOGIN from:self];
    }
    

}


#pragma mark - Table view data source

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case kSection2:
            if (indexPath.row > 0) {
                return [VPPDropDown tableView:tableView heightForRowAtIndexPath:indexPath];
            }
            
        default:
            break;
    }
    
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    int rows = [VPPDropDown tableView:tableView numberOfExpandedRowsInSection:section];
    switch (section) {
        case kSection1:
            rows += kNumberOfRowsInSection1;
            break;
        case kSection2:
            rows += kNumberOfRowsInSection2;
            break;
            
    }
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    
    // Configure the cell...
    cell.textLabel.text = nil;
    
    if ([VPPDropDown tableView:tableView dropdownsContainIndexPath:indexPath]) {
        return [VPPDropDown tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // first check if any dropdown contains the requested cell
    if ([VPPDropDown tableView:tableView dropdownsContainIndexPath:indexPath]) {
        
        if ([_dropDownSelection isExpanded] && indexPath.row == 0) {
            
            CGRect rect = tableView.frame;
            rect.size.height -= 120.0;
            
            tableView.frame = rect;
            
        }
        else if (![_dropDownSelection isExpanded] && indexPath.row == 0){
            
            if (CGRectGetHeight(tableView.frame) < 120.0) {
                CGRect rect = tableView.frame;
                rect.size.height += 120.0;
                
                tableView.frame = rect;
            }
        }
        
        [VPPDropDown tableView:tableView didSelectRowAtIndexPath:indexPath];
        return;
    }
}

#pragma mark - VPPDropDownDelegate
- (void) dropDown:(VPPDropDown *)dropDown elementSelected:(VPPDropDownElement *)element atGlobalIndexPath:(NSIndexPath *)indexPath {
    
    if (dropDown == _dropDownSelection) {
        [self.schholSelectionTable deselectRowAtIndexPath:indexPath animated:YES];
        
        @try {
            
            NSLog(@"%@",[[self.arrayForJsonData objectAtIndex:indexPath.row-1] valueForKey:@"Name"]);
            _selectedIndex = indexPath.row-1;
            
            [self.appDelegate.userDefault setValue:[[self.arrayForJsonData objectAtIndex:indexPath.row-1] valueForKey:@"WebServiceURL"] forKey:SELECTED_SCHOOL_URL];
            [self.appDelegate.userDefault synchronize];
            
            NSLog(@"BASEURL  %@",SUB_BASE_URL);
            
        }
        @catch (NSException *exception) {
            
            NSLog(@"EXC %@",exception);
        }
        @finally {
            
        }
        
        [_dropDownSelection setExpanded:NO];
    }
}

- (UITableViewCell *) dropDown:(VPPDropDown *)dropDown rootCellAtGlobalIndexPath:(NSIndexPath *)globalIndexPath {
    
    return nil;
}
- (UITableViewCell *) dropDown:(VPPDropDown *)dropDown cellForElement:(VPPDropDownElement *)element atGlobalIndexPath:(NSIndexPath *)globalIndexPath {
    static NSString *cellIdentifier = @"CustomDropDownCell";
    
    UITableViewCell *cell = [self.schholSelectionTable dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier] autorelease];
    }
    
    cell.textLabel.text = @"Custom cell";
    cell.detailTextLabel.text = [NSString stringWithFormat:@"row %d",globalIndexPath.row];
    
    return cell;
}


- (CGFloat) dropDown:(VPPDropDown *)dropDown heightForElement:(VPPDropDownElement *)element atIndexPath:(NSIndexPath *)indexPath {
    float height = dropDown.tableView.rowHeight;
    
    return height + indexPath.row * 10;
}

- (void)dealloc {
    [_loginButton release];
    [_baseImageView release];
    [_loginBoxImageView release];
    [_loginFieldBoxImageView release];
    [_userNameFieldImageView release];
    [_passwordFieldImageView release];
    [_userNameTextField release];
    [_passwordTextField release];
    [_loginHighlightedLabel release];
    [_schholSelectionTable release];
    [super dealloc];
}

@end